<template>
  <div>
    <el-button type="primary" @click="clickAddCrops">添加作物</el-button>
    <el-table :data="data.cropsTableData" style="width: 100%">

      <el-table-column prop="cropId" label="作物编号" width="180"> </el-table-column>
      <el-table-column prop="name" label="作物名称" width="180"> </el-table-column>
      <el-table-column  label="操作">
        <template #default="scope">
          <el-button
              type="text"
              size="small"
              @click="clickCropsDetail(scope.row)"
          >作物详情</el-button
          >
          <el-button
              type="text"
              size="small"
              @click="clickProcessDetail(scope.row)"
          >过程详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加农作物对话框 -->
    <el-dialog
        v-model="data.addCropsIsVisible"
        title="记录作物"
    >
      <el-form :model="data.addCropsForm">
        <el-form-item label="作物ID" :label-width="data.formLabelWidth">
          <el-input v-model="data.addCropsForm.cropId" disabled></el-input>
        </el-form-item>
        <el-form-item label="作物名称" :label-width="data.formLabelWidth">
          <el-input v-model="data.addCropsForm.cropName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="原料ID" :label-width="data.formLabelWidth">
          <el-input v-model="data.addCropsForm.materialId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="种植方式" :label-width="data.formLabelWidth">
          <el-input v-model="data.addCropsForm.plantType" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="种植时间" :label-width="data.formLabelWidth">
          <el-input v-model="data.addCropsForm.time" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" :label-width="data.formLabelWidth">
          <el-input v-model="data.addCropsForm.fullAddress" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="原料进货证明" :label-width="data.formLabelWidth">
          <UploadPic @getUploadHash="getHash"/>
        </el-form-item>


      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.addCropsIsVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddCrops">确认</el-button>
          </span>
      </template>
    </el-dialog>
    <!-- 作物详情对话框 -->
    <el-dialog
        v-model="data.cropsDetailVisible"
        title="作物详情"
    >
      <el-descriptions
          class="margin-top"
          title="农作物链上数据详情"
          :column="2"
          border
      >
        <el-descriptions-item label="作物编号">{{data.cropsDetailData.cropId}}</el-descriptions-item>
        <el-descriptions-item label="作物名称">{{data.cropsDetailData.name}}</el-descriptions-item>
        <el-descriptions-item label="种植时间">{{data.cropsDetailData.time}}</el-descriptions-item>
        <el-descriptions-item label="种植方式">{{data.cropsDetailData.plantType}}</el-descriptions-item>
        <el-descriptions-item label="详细地址">{{data.cropsDetailData.produceAddress}}</el-descriptions-item>
        <el-descriptions-item label="原料进货证明" >
          <el-button type="primary" @click="checkCertification(data.cropsDetailData)">查看</el-button>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 通知运输对话框 -->
    <el-dialog
        v-model="data.noticeTrackVisible"
        title="通知运输"
    >
      <el-form :model="data.noticeTrackForm">
        <el-form-item label="农产品编号" :label-width="data.formLabelWidth">
          <el-input v-model="data.noticeTrackForm.cropId" disabled></el-input>
        </el-form-item>
        <el-form-item label="运输公司编号" :label-width="data.formLabelWidth">
          <el-input v-model="data.addCropsForm.cropName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="农户联系方式" :label-width="data.formLabelWidth">
          <el-input v-model="data.addCropsForm.cropName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" :label-width="data.formLabelWidth">
          <el-input v-model="data.addCropsForm.cropName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog v-model="data.certificationVisible">
      <img class="certification" :src="data.certificationSrc" />
    </el-dialog>
  </div>

</template>

<script>
import {onMounted, reactive} from "vue";
import {useStore} from "vuex";
import {useRoute, useRouter} from "vue-router";

import {v1 as uuidv1} from "uuid"
import {

  func_addCrop, func_bindMaterial,
  func_getAddress, func_getMaterialById,
  func_getUserCrops,
  func_getUserInfo,
  func_getUserRole
} from "../../api/etherneum/api";
import UploadPic from "@/components/UploadPic/index";
import ipfsAPI from "ipfs-api";
import {ElMessage} from "element-plus";
const ipfs = ipfsAPI({ host: "49.234.138.61", port: "5001", protocol: "http" });
export default {
  name: "CropsManage",
  components:{
    UploadPic
  },
  setup() {
    const data=reactive({
      address:'',
      currentRole:'',
      curUserInfo:'',
      addCropsIsVisible:false,
      cycleRecordVisible:false,
      cropsDetailVisible:false,
      cropsDetailData:{},
      processDetailVisible:false,
      noticeTrackVisible:false,
      formLabelWidth:'140px',
      noticeTrackForm:{
        cropId:'',
        trackId:''
      },
      cropsTableData : [
      ],
      cropCycleData:{
        seedlingCycle:'',
        irrigationCycle:'',
        fertilizationCycle:"",
        weedingCycle:''
      },
      addCropsForm:{
        cropId:'',
        cropName: '',
        plantType:'',
        time:'',
        certification:'',
        fullAddress:'',
        picId:''
      },
      addMaterialForm:{
        cropId:'',
        materialId:'',
        cropName:'',
        note:'',
        src:''
      },
      materialExist:false,
      addMaterialVisible:false,
      materialData:{},

      certificationVisible:false,
      certificationSrc:''

    })
    const store=useStore();
    const router=useRouter();


    const getAddress = async () => {
      const address = await func_getAddress();
      if (address) {
        store.commit("app/SET_ADDRESS", address);
        let role = await func_getUserRole(address);
        store.commit("app/SET_ROLE", role);
        console.log("getUser address=" + address + " role=" + role);
        data.address = address;
        data.currentRole = role;
        data.curUserInfo = await func_getUserInfo(data.address);
        console.log("cur:" + data.curUserInfo.requestRole);
      }
    };
    const clickAddCrops=()=>{

      if (data.curUserInfo.role!=1&&data.curUserInfo.role!=3){
        ElMessage.error('无权限')
        return
      }
      data.addCropsIsVisible=true
      data.addCropsForm.cropId=uuidv1()

    }
    const  handleAddCrops=async()=>{

      console.log('add Crops')
      if (!data.addCropsForm.certification){
        ElMessage.error('图片未上传')
        return
      }
      let ret=await func_addCrop(data.addCropsForm)
      data.addCropsIsVisible = false
    }

    const getUserCrops=async()=>{
      let res=await func_getUserCrops(data.address)
      if (res) data.cropsTableData=res
      console.log('crops:',data.cropsTableData)
    }


    const clickCropsDetail=(row)=>{
      data.cropsDetailVisible=true;
      data.cropsDetailData=row
    }
    const clickProcessDetail=(row)=>{
      let cropId=row.cropId

      store.commit("crops/UPDATE_STATE_VALUE", {
        cropId: {
          value: cropId,
          session: true
        },
      });
      let url=router.resolve({path: `/Function/cropDetail/${cropId}`})
      window.open(url.href, '_blank');
    }




    const getHash=(hash)=>{
      data.addCropsForm.certification=hash
    }

    const checkCertification=async (row)=>{
      console.log('here')
      let hash=row.certification

      console.log('certification:',row.certification)
      ipfs.get(hash, async (err, result) => {
        console.log('here')
        if (err) throw err;
        let binaryData = [];
        binaryData.push(result[0].content.buffer);
        data.certificationSrc= window.URL.createObjectURL(new Blob(binaryData))
        console.log('src=',data.certificationSrc)
        data.loading=false
      });

      data.certificationVisible=true
    }

    onMounted(()=>{
      getAddress().then(async () => {
        await getUserCrops(data.address)
      });
      ethereum.on("accountsChanged", () => {
        getAddress();
      });
    })
    return {
      data,

      clickAddCrops,

      clickCropsDetail,
      clickProcessDetail,

      handleAddCrops,

      getHash,
      checkCertification
    };
  },
};
</script>

<style lang="scss" scoped>
.certification{
  width: 800px;
}
</style>
